package com.lxc.common;

import java.util.*;
import java.lang.reflect.*;


public class TwoWayTranslateBetweenObjectAndMap{
    public Map<String,Object> objectToMap(Object object){
		HashMap hashMap = new HashMap<String,Object>();
        Class obClass = object.getClass();
		Field[] fields = obClass.getDeclaredFields();
		for(int i = 0; i<fields.length; i++){
			Field templateField = fields[i];
			templateField.setAccessible(true);
			String fieldName = templateField.getName();
			String changedFieldName = bigCaseTo_(fieldName);
			Object templateObject = null;
			try{
			templateObject = templateField.get(object);
			}
			catch(IllegalAccessException e){
			System.out.println("获取属性值失败");
			}
			hashMap.put(changedFieldName,templateObject);
		}
		return hashMap;
    }
	
	//将驼峰命名变成全部小写的，用 _ 连接的命名方法
	private String bigCaseTo_(String name){
		String changedName = "";
		String bigCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		for(int i = 0; i< name.length(); i++){
			String templateChar =""+ name.charAt(i);
			for(int j = 0; j<bigCase.length(); j++){
				String templateChar1 =""+ bigCase.charAt(j);
				if(templateChar.equals(templateChar1)){
					changedName = changedName + "_";
					break;
				}
			}
			changedName = changedName + templateChar.toLowerCase();
		}
		return changedName;
	}
	
	public void mapToObject(Map map,Object object){
		Class obClass = object.getClass();
		Field[] fields = obClass.getDeclaredFields();
		for(int i = 0; i<fields.length; i++){
			Field templateField = fields[i];
			templateField.setAccessible(true);
			String fieldName = templateField.getName();
			String changedName = bigCaseTo_(fieldName);
			try{
			templateField.set(object,map.get(changedName));//会遇到类型转换的问题,是否可以通过 getType()的方法解决？硬编码的方式。
			}
			catch(IllegalAccessException ex){
				System.out.println("设置music属性失败");
				//ex.printStackTrance();
			}
		}

	}
	
}